import time
import json
from core.logger import log
from core.dependencies import get_scheduler, get_redis_service,get_sio
from services.wx_chat_messages import create_wx_messages, get_wx_messages_by_session_id
from services.wx_friends_service import set_friends_remark
from utils.ollama import generate_description
from utils.socket_util import broadcast_message
from utils.rag_api import get_reply_by_rag
sio = get_sio()

@sio.event
async def send_message(sid, data):
    """处理前端发送的消息 - 完整版"""
    try:
        # 解析消息数据
        message_data = parse_message_data(data)

        # 验证必要字段
        if not validate_message(message_data):
            return
        if message_data.get("type")==1:
            # 处理消息
            await handle_text_message(message_data)
        elif message_data.get("type")==3:
            # 处理图片消息
            await handle_image_message(message_data)

    except Exception as e:
        error_msg = f'处理消息失败: {str(e)}'
        print(f'❌ 客户端 {sid} {error_msg}')

def parse_message_data(data):
    """解析消息数据"""
    if isinstance(data, str):
        try:
            return json.loads(data)
        except json.JSONDecodeError:
            return {"type": "text", "content": data}
    elif isinstance(data, dict):
        return data
    else:
        return {"type": "unknown", "content": str(data)}


def validate_message(message_data):
    """验证消息格式"""
    required_fields = ['to_user', 'msg']
    return all(field in message_data for field in required_fields)


async def handle_text_message(message_data):
    # 首先就是将我自己的消息存到数据库中
    await create_wx_messages(message_data["sender"], message_data["to_user"], "回复", message_data["msg"])
    scheduler = await get_scheduler()
    if f"{message_data["sender"]}:{message_data["to_user"]}" in scheduler.monitoring_states:
        # 停止定时任务
        await scheduler.stop_monitoring_task(message_data["sender"], message_data["to_user"])
        await scheduler.process_list_data(message_data["sender"], message_data["to_user"],data_type="image_url",next_content=message_data["msg"])
        return

    reply = await get_reply_by_rag(message_data["msg"], message_data["sender"], message_data["to_user"])
    if "##" in reply:
        msgs = await get_wx_messages_by_session_id(sender_id=message_data["sender"], receiver_id=message_data["to_user"])
        result = await generate_description(msgs)
        log.info(result)
        await set_friends_remark(wx_id=message_data["to_user"], device_id=message_data["sender"], remark=result)
        log.info("设置摘要备注成功！")
        return
    await create_wx_messages(message_data["to_user"], message_data["sender"], "接收", reply)
    await broadcast_message(sio,{"content": reply, "device_id": message_data["sender"], "wx_id": message_data["to_user"]},
                            room=message_data.get('to_user'))


async def handle_image_message(message_data):
    server = await get_redis_service()
    scheduler = await get_scheduler()
    await server.init_redis()
    await create_wx_messages(message_data["sender"], message_data["to_user"], "回复", message_data["msg"],content_type=3)

    await server.set_image_url(message_data["msg"], message_data["sender"], message_data["to_user"])
    await scheduler.start_monitoring_task(message_data["sender"], message_data["to_user"],data_type="image_url")




# Socket.IO 事件处理
@sio.event
async def connect(sid, environ, auth= None):
    if auth:
        pass

@sio.event
async def join(sid, data):
    room = data.get('room')
    if room:
        await sio.enter_room(sid, room)
        log.info(f'{sid} joined room: {room}')

@sio.event
async def leave(sid, data):
    room = data.get('room')
    if room:
        await sio.leave_room(sid, room)
        log.info(f'{sid} left room: {room}')